import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_heating/common/app.dart';
import 'package:flutter_smart_heating/common/http.dart';
import 'package:flutter_smart_heating/mode/list_pagination_model.dart';
import 'package:flutter_smart_heating/ui/src/pull_to_refresh.dart';
import 'package:flutter_smart_heating/ui/ui.dart';
import 'package:syncfusion_flutter_charts/charts.dart';

class InformationIndoorPointTemperaturePage extends StatefulWidget {
  const InformationIndoorPointTemperaturePage({
    super.key,
    this.pointId,
    this.isDialog = false,
  });
  final dynamic pointId;
  final bool isDialog;
  static show(
    context, {
    int? id,
    Map<String, dynamic>? status,
  }) {
    showModalBottomSheet(
      context: context,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(
          top: Radius.circular(UiTheme.boxRadiusX),
        ),
      ),
      showDragHandle: true,
      useSafeArea: true,
      backgroundColor: UiTheme(context).bottomSheetBackgroundColor,
      isScrollControlled: true,
      constraints:
          BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 0.85),
      builder: (context) {
        return InformationIndoorPointTemperaturePage(
          pointId: id,
          isDialog: true,
        );
      },
    );
  }

  @override
  State<InformationIndoorPointTemperaturePage> createState() =>
      _InformationIndoorPointTemperaturePageState();
}

class _InformationIndoorPointTemperaturePageState
    extends State<InformationIndoorPointTemperaturePage> {
  RefreshController refreshController = RefreshController();
  ListPaginationModel pagination = ListPaginationModel();

  Map<String, dynamic> point = {};
  bool loading = true;
  fetchSummary() async {
    var res = await Http.instance
        .post('/api/information/indoor_temperature//point_summary', data: {
      'point_id': widget.pointId,
    });
    if (res.code == 1) {
      setState(() {
        point = res.data;
        loading = false;
      });
    }
  }

  List<dynamic> get chartData {
    var list = [];
    for (var i = 0; i < 5 && i < point['history'].length; i++) {
      list.add(point['history'][i]);
    }
    return list.reversed.toList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: widget.isDialog ? Colors.transparent : null,
      appBar: widget.isDialog
          ? null
          : AppBar(
              title: const Text('室温监测'),
            ),
      body: UiLifeCycle(
        onRouteDone: () {
          fetchSummary();
        },
        child: loading
            ? const Center(child: CupertinoActivityIndicator())
            : Column(
                children: [
                  SizedBox(
                    child: Text(
                      point['name'] ?? '',
                      style: const TextStyle(fontSize: 18),
                    ),
                  ),
                  UiTap(
                    onTap: () {
                      App.push(
                          '/basic/company/detail?id=${point['company_id']}');
                    },
                    child: Opacity(
                      opacity: 0.6,
                      child: Text(
                        '${point['company_name'] ?? ''}',
                      ),
                    ),
                  ),
                  Expanded(
                    child: SingleChildScrollView(
                      padding: const EdgeInsets.all(UiTheme.spacingX),
                      child: SizedBox(
                        width: double.infinity,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            UiPanel(
                              width: double.infinity,
                              height: 150,
                              padding:
                                  const EdgeInsets.only(top: 15, right: 15),
                              child: SfCartesianChart(
                                plotAreaBorderWidth: 0,
                                plotAreaBorderColor:
                                    Colors.grey.withOpacity(0.5),
                                primaryXAxis: CategoryAxis(
                                  axisLine: AxisLine(
                                      width: 0.2,
                                      color: Colors.grey.withOpacity(0.5)),
                                  labelPlacement: LabelPlacement.onTicks,
                                  majorGridLines:
                                      const MajorGridLines(width: 0.1),
                                ),
                                primaryYAxis: NumericAxis(
                                  labelFormat: '{value}°',
                                  axisLine: AxisLine(
                                      width: 0.2,
                                      color: Colors.grey.withOpacity(0.5)),
                                  majorGridLines:
                                      const MajorGridLines(width: 0.1),
                                ),
                                tooltipBehavior: TooltipBehavior(
                                  enable: true,
                                  borderColor: Colors.black26,
                                  color: Colors.black54,
                                  textStyle:
                                      const TextStyle(color: Colors.white),
                                  format: "point.x point.y",
                                ),
                                series: [
                                  SplineSeries<dynamic, String>(
                                    dataSource: chartData,
                                    xValueMapper: (sales, _) => sales['date']
                                        .replaceAll('月', '/')
                                        .replaceAll('日', ''),
                                    yValueMapper: (sales, _) => sales['temper'],
                                    dataLabelMapper: (sales, _) =>
                                        '${sales['temper']}°',
                                    color: Colors.blue,
                                    markerSettings: const MarkerSettings(
                                      isVisible: true,
                                    ),
                                    name: '当日温度',
                                    dataLabelSettings: const DataLabelSettings(
                                      isVisible: true,
                                    ),
                                  )
                                ],
                              ),
                            ),
                            const UiLineBreak(),
                            const Text(
                              '近半月室温数据',
                              style: TextStyle(
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            const SizedBox(height: 10),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: List.generate(
                                  point['history']?.length ?? 0, (index) {
                                var item = point['history'][index];
                                bool isBlock = item['id'] == null;
                                return Container(
                                  decoration: BoxDecoration(
                                    color: index % 2 == 0
                                        ? UiTheme(context).panelBackground
                                        : null,
                                    borderRadius: BorderRadius.circular(
                                        UiTheme.boxRadius),
                                  ),
                                  padding: const EdgeInsets.symmetric(
                                    vertical: 8,
                                    horizontal: 10,
                                  ),
                                  child: Row(
                                    children: [
                                      Expanded(
                                        child: Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            isBlock
                                                ? UiBlock(
                                                    height: 20,
                                                    width:
                                                        MediaQuery.of(context)
                                                                .size
                                                                .width *
                                                            0.8,
                                                  )
                                                : Text(
                                                    item['date'] ?? '',
                                                    style: const TextStyle(
                                                      overflow:
                                                          TextOverflow.ellipsis,
                                                    ),
                                                  ),
                                          ],
                                        ),
                                      ),
                                      const SizedBox(width: 30),
                                      isBlock
                                          ? const UiBlock(
                                              height: 20,
                                              width: 80,
                                            )
                                          : Text(
                                              '${item['temper']}­°C',
                                              style: TextStyle(
                                                color:
                                                    item['status'] == 'abnormal'
                                                        ? Colors.red
                                                        : null,
                                              ),
                                            ),
                                    ],
                                  ),
                                );
                              }),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ],
              ),
      ),
    );
  }
}
